import React, { useEffect, useState, useRef } from "react";
import {
  Button,
  InfiniteScroll,
  List,
  DotLoading,
  SearchBar,
  PullToRefresh,
} from "antd-mobile";
import styles from "./index.less";
import { doFetch, getFetch } from "@/utils/doFetch";
import { FilterFilled } from "@ant-design/icons";
import { useAsyncEffect } from "ahooks";
import { createElement, cloneElement, memo } from "react";
import { Empty, theme } from "antd";
import {
  LightFilter,
  ProFormText,
  ProFormDateRangePicker,
} from "@ant-design/pro-components";
import FormItems from "../InitForm/FormItems";

function upperCase(str) {
  const newStr = str.slice(0, 1).toUpperCase() + str.slice(1);
  return newStr;
}

function useDidUpdateEffect(fn, inputs) {
  const didMountRef = useRef(false);
  useAsyncEffect(async () => {
    if (didMountRef.current) await fn();
    else didMountRef.current = true;
  }, inputs);
}

export default (props) => {
  const {
    actionRef, //表格动作
    formRef, //表单Ref
    rowKey, // key
    columns = [], //columns
    style, //style
    path, //接口地址
    extraparams, //额外参数
    pageSize, //修改默认pageSize
    pagination, //分页设置
    activeTabKey, //激活的tabKey 拖拽表格唯一标识使用 其他情况用不到
    pagetitle, //依赖刷新 （已废弃）
    resizeable = true,
    iscurrent = true,
    children,
  } = props;

  const {
    token: { colorBgSecondary, colorBorder },
  } = theme.useToken();
  const formRefs = formRef ?? useRef();

  const [data, setData] = useState();
  const [hasMore, setHasMore] = useState(true);
  const [pageinfo, setpageinfo] = useState({
    pageIndex: 1,
    pageSize: 8,
  });
  const [searchparams, setsearchparams] = useState({});
  const [open, setopen] = useState(false);

  async function getdata(pageinfo) {
    const append = await getFetch({
      url: path,
      params: {
        ...pageinfo,
        ...extraparams,
        ...searchparams,
      },
    });
    const page = append?.data;
    const dataes = page?.rows ?? append?.data?.dataList ?? [];
    setData((val) => [...(val ?? []), ...dataes]);
    return page
      ? {
          ...page,
          hasNextPage: page.count / 8 > pageinfo.pageIndex,
        }
      : { hasNextPage: false };
  }
  //加载更多数据
  async function loadMore() {
    await setpageinfo((s) => ({
      ...s,
      pageIndex: s?.pageIndex + 1,
    }));
  }

  //刷新
  async function reFresh() {
    //页码重置 数据清空
    await setpageinfo((s) => ({
      ...s,
      pageIndex: 1,
    }));
    await setData(null);
  }

  //额外参数改变后重置
  useAsyncEffect(async () => {
    await reFresh();
    actionRef.current = {
      reload: async () => {
        await reFresh();
      },
    };
  }, [extraparams, searchparams]);

  //分页信息改变后调用数据接口
  useDidUpdateEffect(async () => {
    let page = await getdata(pageinfo);
    setHasMore(page?.hasNextPage);
  }, [pageinfo]);

  return (
    <>
      <div className={styles.header} style={{ backgroundColor: colorBorder }}>
        <div className="center">
          <div className={styles.left}>{pagetitle}</div>
          <div className={styles.right}>
            <div
              className="center"
              style={{ width: 30, height: 30 }}
              onClick={() => {
                setopen(!open);
              }}
            >
              <FilterFilled />
            </div>
          </div>
        </div>
        <div
          className={styles.searchbar}
          style={{
            height: open ? "auto" : 0,
            backgroundColor: colorBgSecondary,
            borderBottom: `1px solid ${colorBorder}`,
          }}
          id="search"
        >
          <div>
            <LightFilter
              formRef={formRefs}
              placement="bottomLeft"
              onValuesChange={(val, vals) => {
                setsearchparams(vals);
              }}
            >
              {columns
                .filter(
                  (it, i) =>
                    it.hideInSearch !== true &&
                    it.valueType !== "option" &&
                    it.valueType !== "split"
                )
                .map((item, index) => {
                  let key = item?.searchvalueType
                    ? upperCase(item?.searchvalueType)
                    : item?.valueType
                    ? upperCase(item?.valueType)
                    : "Input";
                  item.formItemProps = item.formItemProps ?? { rules: [] };
                  if (key === "Input" || key === "Textarea") {
                    return (
                      <ProFormText
                        label={item?.title}
                        name={item.key ?? item.dataIndex}
                        placeholder={`请输入${item.title}`}
                      />
                    );
                  }
                  if (key === "DateRange") {
                    return (
                      <ProFormDateRangePicker
                        label={item?.title}
                        name={item.key ?? item.dataIndex}
                        placeholder={["请选择开始日期", "请选择结束日期"]}
                        fieldProps={{
                          showTime: true,
                        }}
                        width="100%"
                      />
                    );
                  }
                })}
            </LightFilter>
          </div>
        </div>
      </div>
      {data?.length > 0 ? (
        <PullToRefresh
          onRefresh={async () => {
            await reFresh();
          }}
        >
          <div style={{ height:  56 }}></div>
          {data?.map((item, index) =>
            cloneElement(children, { item, columns })
          )}
          <InfiniteScroll loadMore={loadMore} hasMore={hasMore} />
        </PullToRefresh>
      ) : (
        <PullToRefresh
          onRefresh={async () => {
            await reFresh();
          }}
        >
          <div style={{ minHeight: "calc(100vh - 172px)" }}>
            {data?.length === 0 ? (
              <Empty style={{ padding: "64px 0" }} description="暂无数据" />
            ) : (
              <div className="center" style={{ fontSize: 16 }}>
                <DotLoading />
              </div>
            )}
          </div>
        </PullToRefresh>
      )}
    </>
  );
};
